<!-- UserMainPage.vue -->
<template>
  <div class="user-main-page" v-if="isAuthenticated">
    <!-- 头部区域 -->
    <el-header class="header">
      <h2 style="color: #1f2f3d; margin: 0;">求职者工作台</h2>
      <el-button type="danger" size="small" @click="logout">退出登录</el-button>
    </el-header>

    <!-- 主体内容 -->
    <el-container>
      <el-main>
        <el-row :gutter="20">
          <!-- 左侧：个人信息编辑 -->
          <el-col :span="12">
            <el-card header="个人信息管理" shadow="hover">
              <!-- 原有表单内容 -->
              <el-form :model="form" label-width="100px" size="small">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="姓名">
                      <el-input v-model="form.name"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="年龄">
                      <el-input-number v-model="form.age" :min="16" :max="80" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="身份证号">
                      <el-input v-model="form.identity" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="手机号">
                      <el-input v-model="form.phone" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="邮箱">
                      <el-input v-model="form.email" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="所在地">
                      <el-input v-model="form.location" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="期望岗位ID">
                  <el-input-number v-model="form.desiredJobId" :min="1" />
                </el-form-item>
                <el-form-item label="个人简历">
                  <el-input type="textarea" v-model="form.resume" :rows="3" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateUserInfo">保存修改</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>

          <!-- 右侧：简历上传 -->
          <el-col :span="12">
            <el-card header="简历上传" shadow="hover">
              <!-- 原有上传逻辑 -->
              <el-upload
                class="upload-demo"
                drag
                :auto-upload="false"
                :on-change="handleFileChange"
                :file-list="fileList"
                :show-file-list="true">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div slot="tip" class="el-upload__tip">支持 doc/docx/pdf 文件，且不超过 10MB</div>
              </el-upload>

              <div style="margin-top: 20px;">
                <el-button 
                  type="primary" 
                  @click="uploadFile" 
                  :disabled="!selectedFile"
                  :loading="uploadLoading">
                  上传简历
                </el-button>
              </div>

              <div style="margin-top: 20px;">
                <div v-if="currentUser.attachments">
                  <el-alert title="已上传文件" type="success" show-icon :closable="false">
                    <div slot="title">
                      已上传文件: 
                      <a :href="downloadUrl" target="_blank" class="file-link">
                        {{ getFileName(currentUser.attachments) }}
                      </a>
                      <el-button 
                        type="text" 
                        size="small" 
                        @click="downloadFile"
                        icon="el-icon-download">
                        下载
                      </el-button>
                    </div>
                  </el-alert>
                </div>
                <div v-else>
                  <el-alert title="请上传简历文件" type="warning" show-icon :closable="false" />
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 已投递岗位查询区域 -->
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="24">
            <el-card header="已投递岗位" shadow="hover">
              <div style="margin-bottom: 15px;">
                <el-button type="primary" @click="loadDeliveryRecords" :loading="deliveryLoading">刷新列表</el-button>
              </div>
              
              <el-table :data="deliveredJobs" border style="width: 100%" v-loading="deliveryLoading">
                <el-table-column prop="name" label="岗位名称" width="180" />
                <el-table-column prop="salary" label="年薪(万)" width="100" align="center">
                  <template slot-scope="scope">{{ scope.row.salary }}万</template>
                </el-table-column>
                <el-table-column prop="location" label="工作地点" width="120" />
                <el-table-column prop="experience" label="经验要求" width="100" />
                <el-table-column prop="education" label="学历要求" width="100" />
                <el-table-column prop="hrName" label="HR姓名" width="120" />
                <el-table-column prop="deliverTime" label="投递时间" width="180" />
                <el-table-column label="操作" width="150">
                  <template #default="{row}">
                    <el-button size="mini" type="primary" @click="startChat(row)">联系HR</el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <div v-if="deliveredJobs.length === 0 && !deliveryLoading" style="text-align: center; padding: 20px; color: #909399;">
                暂无投递记录
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 底部：职位查询 -->
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="24">
            <el-card header="查找职位" shadow="hover">
              <!-- 原有搜索逻辑 -->
              <el-form :inline="true" :model="query" size="small" style="margin-bottom: 15px;">
                <el-form-item label="岗位名称">
                  <el-input v-model="query.name" placeholder="前端开发" clearable />
                </el-form-item>
                <el-form-item label="工作地点">
                  <el-input v-model="query.location" placeholder="北京" clearable />
                </el-form-item>
                <el-form-item label="最低年薪">
                  <el-input-number v-model="query.salary" :min="0" placeholder="万元" />
                </el-form-item>
                <el-form-item label="学历要求">
                  <el-select v-model="query.education" placeholder="不限" clearable>
                    <el-option label="大专" value="大专" />
                    <el-option label="本科" value="本科" />
                    <el-option label="硕士" value="硕士" />
                    <el-option label="博士" value="博士" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="searchJobs">搜索</el-button>
                  <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>

              <el-table :data="jobList" border style="width: 100%" v-loading="loading">
                <el-table-column prop="name" label="岗位名称" width="180" />
                <el-table-column prop="salary" label="年薪(万)" width="100" align="center">
                  <template slot-scope="scope">{{ scope.row.salary }}万</template>
                </el-table-column>
                <el-table-column prop="location" label="工作地点" width="120" />
                <el-table-column prop="experience" label="经验要求" width="100" />
                <el-table-column prop="education" label="学历要求" width="100" />
                <el-table-column prop="hrId" label="hrid" width="100" align="center" />
                <el-table-column label="操作" width="200">
                  <template #default="{row}">
                    <el-button size="mini" type="primary" @click="startChat(row)">聊天</el-button>
                    <el-button 
                      size="mini" 
                      type="success" 
                      @click="deliverResume(row)" 
                      :disabled="!canDeliver(row)"
                      :title="getDeliverButtonTitle(row)">
                      {{ hasDelivered(row.jobId) ? '已投递' : '投递' }}
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <el-pagination
                @current-change="handlePageChange"
                :current-page="currentPage"
                :page-size="pageSize"
                layout="total, prev, pager, next"
                :total="totalJobs"
                style="margin-top: 15px; text-align: center">
              </el-pagination>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
    <chat-float ref="chatFloat"/>
  </div>

  <!-- 未登录提示 -->
  <div v-else class="unauthorized" style="text-align: center; padding: 60px;">
    <h3>请先登录！</h3>
    <p>正在跳转...</p>
  </div>
</template>

<script>
import request from '@/utils/request';
import ChatFloat from '../ChatFloat.vue';

export default {
  name: 'UserMainPage',
  components: { ChatFloat },
  data() {
    return {
      isAuthenticated: false,
      form: {
        userID: null,
        name: '',
        age: null,
        identity: '',
        phone: '',
        email: '',
        location: '',
        resume: '',
        attachments: '',
        account: '',
        password: '',
        desiredJobId: null
      },
      currentUser: {},
      selectedFile: null,
      fileList: [],
      uploadLoading: false,

      query: { name: '', location: '', salary: undefined, education: '' },
      jobList: [],
      currentPage: 1,
      pageSize: 10,
      totalJobs: 0,
      loading: false,
      
      // 投递记录
      deliveryRecords: [],
      deliveringJobs: [], // 正在投递的岗位ID列表
      deliveredJobs: [], // 已投递的岗位详情
      deliveryLoading: false // 投递记录加载状态
    };
  },
  computed: {
    downloadUrl() {
      if (!this.currentUser.attachments) return '';
      return `/uploads/${encodeURIComponent(this.getFileName(this.currentUser.attachments))}`;
    }
  },
  methods: {
    startChat(row) {
      this.$refs.chatFloat.open(row, 'USER')
    },
    
    checkAuth() {
      const userToken = localStorage.getItem('user_token');
      const userStr = localStorage.getItem('currentUser');
      if (!userToken || !userStr) {
        this.$message.warning('请先登录！');
        this.isAuthenticated = false;
        this.$router.push('/user_login');
        return false;
      }

      this.isAuthenticated = true;
      request.defaults.headers.common['Authorization'] = 'Bearer ' + userToken;

      const userData = JSON.parse(userStr);
      this.form = { ...this.form, ...userData };
      this.currentUser = { ...userData };
      return true;
    },

    async updateUserInfo() {
      try {
        const res = await request.post('/User_updata', this.form);
        if (res.data.code === 1) {
          this.$message.success('信息更新成功！');
          localStorage.setItem('currentUser', JSON.stringify(this.form));
          this.currentUser = { ...this.form };
        } else {
          this.$message.error(res.data.msg || '更新失败');
        }
      } catch (error) {
        this.$message.error('网络错误，请稍后重试');
      }
    },

    handleFileChange(file) {
      this.selectedFile = file.raw;
      this.fileList = [file];
    },

    async uploadFile() {
      if (!this.selectedFile) {
        this.$message.warning('请选择文件');
        return;
      }

      const allowedTypes = [
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/pdf'
      ];
      if (!allowedTypes.includes(this.selectedFile.type)) {
        this.$message.error('只能上传 doc、docx 或 pdf 格式文件');
        return;
      }

      if (this.selectedFile.size > 10 * 1024 * 1024) {
        this.$message.error('文件大小不能超过 10MB');
        return;
      }

      const formData = new FormData();
      formData.append('file', this.selectedFile);
      formData.append('userId', this.form.userID);
      formData.append('name', this.form.name);

      this.uploadLoading = true;
      try {
        const response = await request({
          method: 'post',
          url: '/User_updata_resume',
          data: formData,
          headers: { 'Content-Type': 'multipart/form-data' }
        });

        if (response.data.code === 1) {
          this.$message.success('简历上传成功！');
          this.loadUserAttachment();
          this.fileList = [];
          this.selectedFile = null;
        } else {
          this.$message.error(response.data.msg || '上传失败');
        }
      } catch (error) {
        this.$message.error('上传过程中发生错误');
        console.error(error);
      } finally {
        this.uploadLoading = false;
      }
    },

    getFileName(filePath) {
      if (!filePath) return '';
      return filePath.split('\\').pop().split('/').pop();
    },

    downloadFile() {
      if (!this.currentUser.attachments) return;
      const link = document.createElement('a');
      link.href = this.downloadUrl;
      link.download = this.getFileName(this.currentUser.attachments);
      link.click();
    },

    async loadUserAttachment() {
      try {
        const res = await request.post('/User_get_attachment', { userId: this.form.userID });
        if (res.data.code === 1 && res.data.data.attachments) {
          const path = res.data.data.attachments;
          this.currentUser.attachments = path;
          this.form.attachments = path;
        } else {
          this.currentUser.attachments = null;
        }
      } catch (error) {
        this.currentUser.attachments = null;
        console.error('获取附件失败:', error);
      }
    },

    logout() {
      localStorage.removeItem('user_token');
      localStorage.removeItem('currentUser');
      this.$message.success('已退出登录');
      this.$router.push('/user_login');
    },

    resetQuery() {
      this.query = { name: '', location: '', salary: undefined, education: '' };
      this.currentPage = 1;
      this.searchJobs();
    },

    async searchJobs() {
      this.loading = true;
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          hrId: 0,
          name: this.query.name || '',
          location: this.query.location || '',
          salary: this.query.salary || 0,
          education: this.query.education || ''
        };
        const res = await request.get('/select_job_page', { params });
        if (res.data.code === 1) {
          this.jobList = res.data.data.records || [];
          this.totalJobs = res.data.data.total || 0;
          
          // 加载投递记录
          this.loadDeliveryRecords();
        } else {
          this.$message.error(res.data.msg || '查询失败');
        }
      } catch (error) {
        this.$message.error('网络异常');
      } finally {
        this.loading = false;
      }
    },

    handlePageChange(page) {
      this.currentPage = page;
      this.searchJobs();
    },
    
    // 检查是否可以投递
    canDeliver(job) {
      // 检查是否有HR ID
      if (!job.hrId) return false;
      
      // 检查是否有简历
      if (!this.currentUser.attachments) return false;
      
      // 检查是否正在投递
      if (this.deliveringJobs.includes(job.jobId)) return false;
      
      // 检查是否已投递
      if (this.hasDelivered(job.jobId)) return false;
      
      return true;
    },
    
    // 获取按钮提示文案
    getDeliverButtonTitle(job) {
      if (!job.hrId) return '该岗位未指定HR';
      if (!this.currentUser.attachments) return '请先上传简历';
      if (this.deliveringJobs.includes(job.jobId)) return '正在投递...';
      if (this.hasDelivered(job.jobId)) return '已投递';
      return '投递简历';
    },
    
    // 检查是否已投递
    hasDelivered(jobId) {
      return this.deliveryRecords.includes(jobId);
    },
    
    // 投递简历
    async deliverResume(job) {
      // 添加到正在投递列表
      this.deliveringJobs.push(job.jobId);
      
      const loading = this.$loading({
        lock: true,
        text: '正在投递...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {
        const res = await request.post('/api/deliver_resume', {
          userId: this.form.userID,
          jobId: job.jobId,
          hrId: job.hrId,
          resumePath: this.currentUser.attachments
        });

        if (res.data.code === 1) {
          this.$message.success('简历投递成功！');
          // 添加到已投递记录
          this.deliveryRecords.push(job.jobId);
        } else {
          this.$message.error(res.data.msg || '投递失败');
        }
      } catch (error) {
        this.$message.error('网络异常，请稍后再试');
        console.error('投递失败:', error);
      } finally {
        loading.close();
        // 从正在投递列表中移除
        const index = this.deliveringJobs.indexOf(job.jobId);
        if (index > -1) {
          this.deliveringJobs.splice(index, 1);
        }
      }
    },
    
    // 加载投递记录
    async loadDeliveryRecords() {
      this.deliveryLoading = true;
      try {
        // 获取投递的岗位ID列表
        const res = await request.post('/api/get_delivery_records', {
          userId: this.form.userID
        });
        
        if (res.data.code === 1) {
          this.deliveryRecords = res.data.data || [];
          
          // 获取每个岗位的详细信息
          await this.loadDeliveredJobDetails();
        }
      } catch (error) {
        console.error('加载投递记录失败:', error);
        this.$message.error('加载投递记录失败');
      } finally {
        this.deliveryLoading = false;
      }
    },
    
   // 加载已投递岗位的详细信息
async loadDeliveredJobDetails() {
  try {
    // 直接通过用户ID获取已投递岗位的详细信息
    const res = await request.post('/api/get_delivered_jobs_by_user', {
      userId: this.form.userID
    });
    
    if (res.data.code === 1) {
      this.deliveredJobs = res.data.data || [];
    } else {
      this.deliveredJobs = [];
    }
  } catch (error) {
    console.error('加载岗位详情失败:', error);
    this.deliveredJobs = [];
  }
}
  },
  created() {
    const userToken = localStorage.getItem('user_token');
    
    if (userToken) {
      request.defaults.headers.common['Authorization'] = 'Bearer ' + userToken;
    } else {
      this.$message.warning('请先登录');
      return this.$router.push('/user_login');
    }

    this.checkAuth();
    this.loadUserAttachment();
    this.searchJobs();
  }
};
</script>

<style scoped>
.user-main-page {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  padding: 10px 0;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
}
.file-link {
  color: #409EFF;
  text-decoration: none;
  margin-right: 10px;
}
.file-link:hover {
  text-decoration: underline;
}
</style>